<template>
  <el-dialog class="public-dialog" title="导入" :modelValue="modelValue" align-center width="560" @close="handleClose" :close-on-click-modal="false">
    <p class="text-[14px] text-[#0a1431] leading-[20px] mb-[8px]">第 <span class="font-[600]">1</span> 步：点击下载模版</p>
    <a :href="downloadUrl" class="bg-[#FAFAFA] flex items-center justify-center rounded-[4px] py-[12px] cursor-pointer">
      <div class="text-[#3366F1] flex items-center gap-1">
        <div class="dk-iconfont icon-Download"></div>
        下载模板
      </div>
    </a>
    <p class="text-[14px] text-[#0a1431] leading-[20px] my-[16px]">第 <span class="font-[600]">2</span> 步：按照模版要求填写</p>
    <p class="text-[14px] text-[#0a1431] leading-[20px] mb-[8px]">第 <span class="font-[600]">3</span> 步：上传填写完成的文件</p>
    <el-upload
      ref="upload"
      v-model:file-list="fileList"
      accept=".csv,.xml,.xlsx"
      class="v-import"
      drag
      :data="extraData"
      :action="ossParams.host ? `${ossParams.host}` : ''"
      :limit="1"
      :auto-upload="false"
      :on-exceed="handleExceed"
      :before-upload="beforeUpload"
      :on-error="handleUploadError"
      :on-success="handleUploadSuccess"
    >
      <div class="text-[#3366F1] flex items-center">
        <div class="dk-iconfont icon-Plus"></div>
        上传文件
      </div>
    </el-upload>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :loading="loadings.submit" :disabled="!fileList.length" @click="submit"> 保存 </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElMessage, ElMessageBox, genFileId, ElNotification } from "element-plus"
import { ref } from "vue"
const load = ref(false)

import { uploadSignUrl } from "@/api/public"

const props = defineProps({
  modelValue: { type: Boolean, default: "" },
  importUrl: { type: String, default: "" },
  callBack: {
    type: Function,
    default: (query) => query,
  },
  downloadUrl: { type: String, default: "" },
  tableRef: { type: Object, default: () => ({}) },
  task: Boolean,
})

let loadings = reactive({})
let ossParams = reactive({
  host: "",
})

const emit = defineEmits(["close", "update:modelValue"])

const fileList = ref([])
const upload = ref()
const extraData = reactive({})
const uploadPercent = ref(0)
const fileName = ref("")

const handleExceed = (files) => {
  upload.value?.clearFiles()
  const file = files[0]
  file.uid = genFileId()
  upload.value?.handleStart(file)
}

const get_suffix = (name) => {
  const pos = name.lastIndexOf(".")
  let suffix = ""
  if (pos != -1) {
    suffix = name.substring(pos)
  }
  return suffix
}

const beforeUpload = (file) => {
  if (file.size > 1024 * 1024 * 1024) {
    ElMessage.warning("上传文件大小不能超过1G")
    return false
  }
  uploadPercent.value = 0
  try {
    const { policy, accessid, dir, signature } = ossParams || {}
    // const name = `${file.name.split('.')[0]}_${new Date()}_${new Date().getTime()}`
    const name = `${file.name.split(".")[0]}_${new Date().getTime()}`
    const _fileName = name + get_suffix(file.name)
    extraData.key = dir + _fileName
    extraData.policy = policy
    extraData.OSSAccessKeyId = accessid
    extraData.signature = signature
    fileName.value = _fileName
    return true
  } catch (err) {
    fileName.value = ""
    console.log(err)
    ElMessage.error(err.message)
    return false
  }
}

const handleUploadSuccess = () => {
  const [{ downloadUrl }] = arguments
  console.error("ar", arguments)
  if (props.callBack && typeof props.callBack === "function") {
    props.callBack({
      downloadUrl,
      fileName: fileName.value,
      ossUrl: extraData.key,
    })
  }
}

const handleUploadError = (err) => {
  fileName.value = ""
  ElMessage.error(`上传失败 ${err.toString()}`)
  uploadPercent.value = 0
}

// 打开弹窗
const open = async (selection) => {
  if (!load.value) {
    load.value = true
    await 1
  }
  loadings = reactive({})
}
// 关闭弹窗
const handleClose = () => {
  emit("update:modelValue", false)
  fileList.value = []
}

// 提交
const submit = () => {
  // loadings.submit = true
  loadings.submit = false
  upload.value.submit()
  // const params = new FormData()
  // fileList.value.forEach(d => {
  //   params.append('file', d.raw)
  // })
  // let dtd = props.importUrl
  // if (props.paramsFormatter && typeof props.paramsFormatter === 'function') {
  //   dtd = props.paramsFormatter(props.importUrl)
  // }
  // api
  //     .submit(props.importUrl, params)
  //     .then(res => {
  //       const skip = res.data?.skip || []
  //       if (res.code === 200) {
  //         emit('success')
  //         ElMessage.success('导入成功')
  //         close()
  //         return
  //       }
  //       if (skip.length) {
  //         ElMessageBox({
  //           title: '导入提示',
  //           confirmButtonText: '跳过导入',
  //           cancelButtonText: '取消导入',
  //           message: h('p', null, [
  //             skip.map(d =>
  //                 h('p', null, `第${d}行中的站点/销售/sku/部门不存在，`)
  //             ),
  //             h('p', null, '是否跳过导入?'),
  //           ]),
  //         })
  //             .then(() => {
  //               skip.forEach(d => {
  //                 params.append('skip[]', d)
  //               })
  //               api.submit(props.importUrl, params).then(res => {
  //                 emit('success')
  //                 ElMessage({ type: 'success', message: '导入成功' })
  //                 close()
  //               })
  //             })
  //             .catch(() => {
  //               ElMessage({ type: 'info', message: '取消操作' })
  //             })
  //       } else {
  //         ElNotification.error({ title: res.message })
  //       }
  //     })
  //     .finally(() => {
  //       loadings.submit = false
  //     })
}
const initUpload = async () => {
  // const { data } = await uploadSignUrl({ dir: 'import/expense/' })
  const { data } = await uploadSignUrl({ dir: "import/tracking_number/" })
  console.warn(data)
  ossParams = {
    ...data?.signature,
  }
}

onMounted(() => {
  // initUpload()
})

defineExpose({ open, initUpload })
</script>

<style lang="scss" scoped>
.v-import {
  :deep(.el-upload-dragger) {
    padding: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-color: #3366f1;
  }
}
</style>
